<template>
  <div class="page-container">
    <el-form
        v-if=" activeName == 'first'"
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="rule-form"
        size="small"
        status-icon
    >
      <el-form-item >
        <el-row>
          <el-col :span="24">{{inviteInfo.inviteUserName}}邀请您加入</el-col>
          <el-col :span="24">
            {{inviteInfo.enterpriseName}} <el-tag class="ml-2" effect="dark" :type="inviteInfo.isAuth == '0'?'danger':'success'">{{inviteInfo.isAuth == '0'?'未认证':'已认证'}} </el-tag></el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="ruleForm.name"/>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="ruleForm.phone" maxlength="11"/>
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <div style="display:flex;">
            <div style="width: 150px;margin-right: 20px">
              <el-input v-model="ruleForm.code" />
            </div>
          <div>
            <el-button :disabled="butDisable" @click="getPhoneCode">{{butText}}</el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">立即加入</el-button>
      </el-form-item>
    </el-form>


    <div v-if=" activeName == 'second'">
      <h2>操作成功</h2>
      <div>您已完成加入{{inviteInfo.enterpriseName}}，等待管理审批（ {{butTime}} s）</div>
    </div>



    <div v-if=" activeName == 'third'">
      <h2>加入成功</h2>
      <div>您已成功加入{{inviteInfo.enterpriseName}}.进入企业，与同事开启高效协作</div>
      <div><el-button type="primary" @click="switchNewEnterprise">切换至新企业</el-button></div>
    </div>
    <el-empty v-if=" activeName == 'fouth'" description="邀请码已过期">
    <el-button type="primary" size="small" @click="goBack">返回</el-button>
  </el-empty>
  </div>
</template>

<script>
import {reactive, toRefs, onMounted,ref,computed} from 'vue'
import {useRoute,useRouter} from 'vue-router'
import { ElMessage } from 'element-plus'
import {shareSign} from "/@/api/sys/dept"
import { getCode, registerLogin, setEnterprise } from '/@/api/login';
import { Session,Local } from '/@/utils/storage'
import Cookies from 'js-cookie'
import { useThemeConfig } from '/@/stores/themeConfig'
import { initFrontEndControlRoutes } from '/@/router/frontEnd'
import { initBackEndControlRoutes } from '/@/router/backEnd'
import { storeToRefs } from 'pinia'
import { formatAxis } from '/@/utils/formatTime'
import { NextLoading } from '/@/utils/loading'
import { useI18n } from 'vue-i18n'
export default {
  name: "register",
  setup() {
    const route = useRoute()
    const router = useRouter()
    const  ruleFormRef = ref()
    const storesThemeConfig = useThemeConfig()
    const { themeConfig } = storeToRefs(storesThemeConfig)
    const { t } = useI18n()
    const state = reactive({
      isNorRegister: false,
      formSize: 'small',
      ruleForm: {
        name: '',
        phone: '',
        code:''
      },
      rules:{
        name: [
          { required: true, message: '请输入您的姓名', trigger: 'blur' },
          { min: 2, max: 64, message: '最少需要两个汉字', trigger: 'blur' },
        ],
        phone:[
          {
            required: true,
            message: "手机号不能为空",
            trigger: "blur",
          },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        code:[ {
          required: true,
          message: "请输入验证码",
          trigger: "blur",
        },]
      },
      activeName: 'first',
      inviteInfo:{},
      butDisable:false,
      butText: '获取验证码',
      butTime: 3,
      loginSuccessInfo:{}
    })


    const submitForm = async (formEl) => {
      if (!formEl) return
      await formEl.validate((valid, fields) => {
        if (valid) {
          let sendData = {
            username:state.ruleForm.phone,
            nickname:state.ruleForm.name,
            code:state.ruleForm.code,
            enterpriseId:state.inviteInfo.enterpriseId,
            isAudit:state.inviteInfo.isApprove,
            deptId: state.inviteInfo.deptId,
            deptType: state.inviteInfo.type
          }
          registerLogin(sendData).then(res=>{
            state.loginSuccessInfo = res.data
              if(state.inviteInfo.isApprove == '0'){
                state.activeName = 'third'
              }else{
                state.activeName = 'second'
                joinSuccessCountdown()

              }
          })
        } else {
          console.log('error submit!', fields)
        }
      })
    }

    const resetForm = (formEl) => {
      if (!formEl) return
      formEl.resetFields()
    }

    const getPhoneCode = () => {
      if (state.ruleForm.phone == '' || state.ruleForm.phone == null) {
        ElMessage.error('请输入手机号!')
      } else {
        state.butDisable = true
        codeCountdown()
        getCode({ phone: state.ruleForm.phone }).then(res => {
          if (res.code == 0) {
            ElMessage.success('短信已发送!')
          } else {
            ElMessage.error('发送失败!')
          }
        })
      }
    }

    const codeCountdown = () => {
      let time = 60
      const interver = setInterval(() => {
        time--
        if (time <= 0) {
          state.butDisable = false
          state.butText = '获取验证码'
          clearInterval(interver)
        } else {
          state.butText = '重新获取（' + time + '）秒'
        }
      }, 1000)
    }


    const joinSuccessCountdown = () => {
      let time = 3
      const interver = setInterval(() => {
        time--
        if (time <= 0) {
          state.butTime = 0
          clearInterval(interver)
          router.push({
            path: '/login'
          })
        } else {
          state.butTime = time
        }
      }, 1000)
    }

    const switchNewEnterprise = () => {
      let data = state.loginSuccessInfo
      // 存储 token 到浏览器缓存
      Session.set('token', data.token)
      Cookies.set('userId', data.userId)
      Cookies.set('userName', data.nickname)
      Cookies.set('enterpriseName', state.inviteInfo.enterpriseName)
      setEnterprise(state.inviteInfo.enterpriseId).then(res=>{
        if(res.code == 0){
          // 登录成功 初始化
          // proxy.initialize()
          // TODO 获取路由菜单.....
          // 模拟数据，对接接口时，记得删除多余代码及对应依赖的引入。用于 `/src/stores/userInfo.ts` 中不同用户登录判断（模拟数据）
          if (!themeConfig.value.isRequestRoutes) {
            // 前端控制路由，2、请注意执行顺序
            initFrontEndControlRoutes()
            signInSuccess()
          } else {
            // 模拟后端控制路由，isRequestRoutes 为 true，则开启后端控制路由
            // 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
            initBackEndControlRoutes()
            // 执行完 initBackEndControlRoutes，再执行 signInSuccess
            signInSuccess()
          }
        }
      })
    }
    const signInSuccess = () => {
      // 初始化登录成功时间问候语
      let currentTimeInfo = currentTime.value
      router.push('/')
      // 登录成功提示
      const signInText = t('message.signInText')
      ElMessage.success(`${currentTimeInfo}，${signInText}`)
      // 添加 loading，防止第一次进入界面时出现短暂空白
      NextLoading.start()
    }

    // 时间获取
    const currentTime = computed(() => {
      return formatAxis(new Date())
    })

    const goBack = () => { 
      router.push('/')
    }

    onMounted(() => {
      if (route.query.shareKey) {
        state.isNorRegister = true
        shareSign({jedisId:route.query.shareKey}).then(res=>{
          if(res.code == 0){
            state.inviteInfo = res.data
          }
        })
      } else {
        state.isNorRegister = false
      }
    })


    return {
      ...toRefs(state),
      submitForm,
      resetForm,
      ruleFormRef,
      getPhoneCode,
      codeCountdown,
      joinSuccessCountdown,
      switchNewEnterprise,
      currentTime,
      signInSuccess,
      goBack
    }
  }
}
</script>

<style lang="scss" scoped>
.page-container {
  margin: 0 auto;
  width: 400px;
  .rule-form{
    margin-top: 200px;
  }
}
</style>
